package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 苏成博
 * @date 2023-02-08 10:52
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Transactional
    public void saveDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //新增菜品
        dishMapper.saveDish(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //循环为集合的每一个口味加上菜品的id
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        //新增口味.新增的是个数组
        dishFlavorMapper.saveDishFlavors(flavors);
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 根据ids批量删除菜品
     * 下面实现，是用户同时点击了起售和未起售的菜品，在批量删除时只删除未起售的菜品，保留起售的商品，同时提醒用户
     * 用户同时点击了有套餐关联没有套餐关联的菜品，在批量删除时只删除没有套餐关联的菜品，保留套餐关联的商品，同时提醒用户
     * @param ids
     */
    /*@Override
    public void deleteByIds(String ids) {
        //根据，切割字符串
        String[] split = ids.split(",");
        List<Integer> list=new ArrayList<>();
        int flag1=0;//用于记住菜品是否已停售,0：停售/1：起售
        int flag2=0;//用于记住菜品是否和套餐关联，0：未关联/1：关联
        Dish dish=null;
        //将其全部变为int类型加入list集合
        for (int i = 0; i < split.length; i++) {
            try {
                int id = Integer.parseInt(split[i]);
                dish = dishMapper.findById(id);
                if (dish.getStatus()==1){
                    flag1=1;//表示批量删除选中的菜品中有未停售的菜品
                    continue;
                }
                Integer count = setmealDishMapper.findByDishId(id);
                if (count>0){
                    flag2=1;//表明有菜品关联了套餐不能删除
                    continue;
                }
                list.add(id);
            } catch (NumberFormatException e) {
                throw new DeletionNotAllowedException("请传入正确的需要删除的菜品！！！");
            }
        }
        dishMapper.deleteByIds(list);
        if (flag1==1){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        if (flag2==1){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
    }*/

    /**
     * 根据ids批量删除菜品
     *
     * @param ids
     */
    @Transactional
    public void deleteByIds(String ids) {
        //根据，切割字符串
        String[] split = ids.split(",");
        List<Integer> list = new ArrayList<>();
        Dish dish = null;
        //将其全部变为int类型加入list集合
        for (int i = 0; i < split.length; i++) {
            try {
                int id = Integer.parseInt(split[i]);
                dish = dishMapper.findById(id);
                if (dish.getStatus() == 1) {
                    throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                }
                Integer count = setmealDishMapper.findByDishId(id);
                if (count > 0) {
                    throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
                }
                list.add(id);
            } catch (NumberFormatException e) {
                throw new DeletionNotAllowedException(MessageConstant.ERROR_CATEGORY);
            }
        }
        dishFlavorMapper.deleteDishFlavors(list);
        dishMapper.deleteByIds(list);
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public DishVO findById(Integer id) {
        //根据id查询初菜品
        Dish dish = dishMapper.findById(id);
        //创建DishVO对象
        DishVO dishVO = new DishVO();
        //根据dishId查询出口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.findByDishId(dish.getId());
        //将属性拷贝至dishVO中
        dishVO.setFlavors(dishFlavors);
        BeanUtils.copyProperties(dish, dishVO);
        //返回dishVO对象
        return dishVO;
    }

    /**
     * 更新菜品信息
     *
     * @param dishDTO
     */
    /*@Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        DishFlavor dishFlavor=null;
        //更新口味表
        for (int i = 0; i < flavors.size(); i++) {
            dishFlavor = flavors.get(i);
            //如若没传口味信息则跳过本次循环
            if (dishFlavor.getName() == null || "".equals(dishFlavor.getName())) {
                continue;
            }
            //如果新增了口味信息那么将其插入口味表中
            if (dishFlavor.getDishId() == null) {
                //如果dishId=0那就新增这条口味数据
                dishFlavor.setDishId(dishDTO.getId());
                dishFlavorMapper.saveDishFlavor(dishFlavor);
                continue;
            }
            //如果修改了口味信息，则修改口味表
            dishFlavorMapper.updateFlavor(dishFlavor);
        }
        //更新dish表
        dishMapper.updateDish(dish);
    }*/

    /**
     * 优化版更新菜品信息
     * @param dishDTO
     */
    @Transactional
    public void updateDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //现根据dishId删除dish_flavor表中的数据
        dishFlavorMapper.deleteDishFlavorByDishID(dishDTO.getId());
        //新增口味信息
        List<DishFlavor> listFlavors=dishDTO.getFlavors();
        listFlavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDTO.getId()));
        if (listFlavors.size()>0) {
            dishFlavorMapper.saveDishFlavors(listFlavors);
        }
        //更新dish表
        dishMapper.updateDish(dish);
    }

    /**
     * 根据categoryId在dish表中查询多条数据
     * @param categoryId
     * @return
     */
    public List<Dish> findByCategoryId(Integer categoryId) {
        List<Dish> dishList=dishMapper.findByCategoryId(categoryId);
        return dishList;
    }

    /**
     * 根据CategoryId查询出菜品集合并封装口味信息
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> findUDishByCategoryId(Integer categoryId) {
        List<Dish> dishList = dishMapper.findByCategoryId(categoryId);
        List<DishVO> dishVOList=new ArrayList<>();
        DishVO dishVO = null;
        for (int i = 0; i < dishList.size(); i++) {
            //新建一个DishVO对象
            dishVO=new DishVO();
            //从集合中取出一个dish对象，将其属性复制给DishVO
            Dish dish = dishList.get(i);
            BeanUtils.copyProperties(dish,dishVO);
            //根据dishId查询出口味信息集合
            List<DishFlavor> dishFlavors = dishFlavorMapper.findByDishId(dish.getId());
            //将口味信息集合赋值给DishVO对象
            dishVO.setFlavors(dishFlavors);
            //将dishVO对象加入集合中
            dishVOList.add(dishVO);
        }
        return dishVOList;
    }

    @Override
    public void updateDishStatus(Integer status, Long id) {
        dishMapper.updateDishStatus(status,id);
    }

    @Override
    public List<Dish> findDishByName(String name) {
        List<Dish> dishList=dishMapper.findDishByName(name);
        return dishList;
    }
}
